﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using Jok.Server.Infrastructure;

namespace Jok.Server.Main
{
    public class MainService : JokService, IMainService
    {
        #region Messages
        private const string ERR_CONNECT = "Error while connecting service: {0}. Error: {1}";
        private const string ERR_DISCONNECT = "Error while disconnecting service: {0}. Error: {1}";
        private const string ERR_SEND_COMMAND = "Error while sending command to service: {0}. Error: {1}";
        private const string ERR_ALREADY_LOGINED = "Error user already loged in, and tried it again, User Ticket: {0}";
        private const string ERR_UNAUTHORIZED = "Anauthorized command appears. Command: {0}";
        #endregion

        static Dictionary<int, JokServiceClient> Services { get; set; }

        static MainService()
        {
            Services = new Dictionary<int, JokServiceClient>();
        }

        public bool Connect(int id)
        {
            try
            {
                InstanceContext instanceContext = new InstanceContext(new CallbackHandler());
                JokServiceClient client = new JokServiceClient(instanceContext, id.ToString());

                client.Open();
                Services.Add(id, client);
            }
            catch (Exception ex) { LogMng.WriteWarning(ERR_CONNECT, id, ex); return false; }

            return true;
        }
        public bool Disconnect(int id)
        {
            try
            {
                Services[id].Close();
                Services.Remove(id);
            }
            catch (Exception ex) { LogMng.WriteWarning(ERR_DISCONNECT, id, ex); return false; }

            return true;
        }
        public bool IsConnected(int id)
        {
            return (Services.ContainsKey(id) && Services[id].State == CommunicationState.Opened);
        }

        public void Command(int ServiceId, JokCommand Command)
        {
            try
            {
                #region UnAuthorization Error
                if (ServiceId != -1 && !Tickets.ContainsKey(CurrentTicket))
                {
                    LogMng.WriteWarning(ERR_UNAUTHORIZED, Command);
                    return;
                }
                #endregion

                //OperationContext.Current.OutgoingMessageHeaders.Add(System.ServiceModel.Channels.MessageHeader.CreateHeader("MyClientHeader", "http://silverlight.net", "..."));


                Services[ServiceId].CommandReceived(Tickets[CurrentTicket].UserId, CurrentTicket, Command);
            }
            catch (Exception ex) { LogMng.WriteWarning(ERR_SEND_COMMAND, ServiceId, ex); }
        }

        private void ProcessUserCommand(IJokServiceCallback Callback, JokCommand Command)
        {
            Guid Ticket = Guid.NewGuid();

            RegisterTicket(Ticket);
            Tickets[Ticket].UserId = 1;
        }
    }

    public class CallbackHandler : IJokServiceCallback
    {
        public void Command(Guid Ticket, JokCommand Command)
        {
            MainService.Tickets[Ticket].SendCommand(Command);
        }
    }
}
